package com.movefeng.hexoblogadmin.config.task;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.movefeng.hexoblogadmin.model.Comment;
import com.movefeng.hexoblogadmin.model.User;
import com.movefeng.hexoblogadmin.service.CommentService;
import com.movefeng.hexoblogadmin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Auther: csp1999
 * @Date: 2021/02/09/16:30
 * @Description: 多线程定时任务，用于同步评论和活跃用户信息到数据
 */
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@Slf4j
public class MultithreadScheduleTask{

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    /**
     * 定时任务方式一:
     * 定时同步评论数据到mysql
     * @throws InterruptedException
     */
    @Async
    @Scheduled(fixedDelay = 1000*3*60)  // 间隔3分钟同步一次
    public void loadData() throws InterruptedException {
        log.info("评论同步定时任务执行...");
        AVOSCloud.useAVCloudCN();
        AVOSCloud.initialize("xxxx",
                "xxx",
                "xxx");

        AVQuery<AVObject> query = new AVQuery<>("Comment");

        // SpringBoot定时任务，定时3分钟获取一次博客评论数据，并同步到博客中
        try {
            List<AVObject> objects = query.find();
            // 评论集合
            List<Comment> commentList = new ArrayList<>();
            // 用户集合
            Set<User> users = new HashSet<>();

            objects.forEach(object -> {
                Comment comment = new Comment();
                User user = new User();

                comment.setId(object.getObjectId());
                comment.setUserName(object.get("nick").toString());

                // 父评论id，如果为null则是顶级评论
                if (object.get("pid")!=null){
                    AVQuery<AVObject> query2 = new AVQuery<>("Comment");
                    query2.whereEqualTo("objectId",object.get("pid"));
                    try {
                        List<AVObject> objects2 = query2.find();
                        comment.setParentName(objects2.get(0).get("nick").toString());
                    } catch (AVException e) {
                        e.printStackTrace();
                    }
                }else {
                    comment.setParentName("");
                }

                Date date = object.getCreatedAt();
                //System.out.println(date);
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //String format = sdf.format(date);
                comment.setCreateTime(date);
                comment.setArticleUrl(object.get("url").toString());
                comment.setContent(object.get("comment").toString());// <p>😀博客评论测试！</p>
                comment.setAuditStatus(1);
                comment.setEmail(object.get("mail").toString());

                String email = object.get("mail").toString();
                String[] split = email.split("@");
                String avatarStr = "https://gravatar.loli.net/avatar/b388f34604b8e82ca12f4b65c320c44d?d=mp&v=1.3.10";
                if (split[1].equalsIgnoreCase("qq.com")){
                    avatarStr = "http://q1.qlogo.cn/g?b=qq&nk="+split[0]+"&s=100";
                }
                user.setEmail(object.get("mail").toString());
                user.setName(object.get("nick").toString());
                user.setWebsite(object.get("link").toString());
                user.setAvatar(avatarStr);

                users.add(user);
                commentList.add(comment);
            });

            // Set转List
            List<User> userList = new ArrayList<>();
            userList.addAll(users);
            // 批量更新
            commentService.updateCommentBatch(commentList);
            userService.updateUserBatch(userList);
        } catch (AVException e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时任务方式二: 需要实现 SchedulingConfigurer 接口
     * @param taskRegistrar
     */
//    @Override
//    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//    }

}